﻿using System;
using FarseerGames.FarseerPhysics.Mathematics;
using FreeGoo.GameEngine.Renderables;

namespace FreeGoo.GameEngine.Behaviors
{
    public class Rotator : Behavior
    {
        private const float DefaultRotatorSpeed = 0.5f;
        private Vector2 _initialPosition;
        private float _initialRotation;

        private float _initialPositionRotation;
        private Vector2 _center;

        public Rotator(Renderable renderable)
            : base(renderable)
        {
            _initialPosition = renderable.Position;
            _initialRotation = renderable.Rotation;
            _center = _initialPosition;
            PrepareVariables();
            Speed = DefaultRotatorSpeed;
        }

        public Vector2 Center 
        { 
            get 
            { 
                return _center; 
            } 

            set 
            { 
                _center = value; 
                PrepareVariables(); 
            } 
        }

        public float Speed { get; set; }
        public float Rotation { get; set; }
        public float RotationOffset { get; set; }
        public float Distance { get; set; }

        public override void Update()
        {
            Rotation += Speed * Renderable.Engine.TimeStep;
            Renderable.Rotation = Rotation + _initialRotation + RotationOffset;
            Vector2 pos = Center + new Vector2(
                (float)Math.Cos(Rotation + _initialPositionRotation + RotationOffset) * Distance,
                (float)Math.Sin(Rotation + _initialPositionRotation + RotationOffset) * Distance);

            Vector2 delta = pos - Renderable.Position;

            Renderable.Position = pos;

            if (Renderable is BodyRenderable)
            {
                BodyRenderable bodyRenderable = Renderable as BodyRenderable;
                bodyRenderable.Body.LinearVelocity = delta / Renderable.Engine.TimeStep;
                bodyRenderable.Body.AngularVelocity = Speed;
            }
        }

        private void PrepareVariables()
        {
            Vector2 delta = _initialPosition - Center;
            Distance = delta.Length();
            _initialPositionRotation =
                (float)Math.Atan2(
                    delta.Y,
                    delta.X);
        }
    }
}
